// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ListUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.IssuOrder;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.IssuOrderMapper;
import com.fowo.api.mapper.NavLogisticsChannelViewMapper;
import com.fowo.api.mapper.NavLogisticsProviderViewMapper;
import com.fowo.api.mapper.NavSellOrderDeclareMapper;
import com.fowo.api.mapper.NavSellOrderDetailMapper;
import com.fowo.api.mapper.NavSellOrderPlatformMapper;
import com.fowo.api.mapper.NavSellOrderTransactionMapper;
import com.fowo.api.mapper.ShopInfoMapper;
import com.fowo.api.mapper.SysRegionMapper;
import com.fowo.api.model.issu.order.IssuOrderExcelPo;
import com.fowo.api.model.issu.order.IssuOrderImportPo;
import com.fowo.api.model.issu.order.IssuOrderItemVo;
import com.fowo.api.model.issu.order.IssuOrderMarkDeliveryAction;
import com.fowo.api.model.issu.order.IssuOrderSearchParamPo;
import com.fowo.api.model.issu.order.IssuOrderUnMarkDeliveryAction;
import com.fowo.api.model.issu.order.IssuOrderVo;
import com.fowo.api.model.nav.logistics.channel.view.NavLogisticsChannelViewItemVo;
import com.fowo.api.model.nav.logistics.channel.view.NavLogisticsChannelViewSearchParamPo;
import com.fowo.api.model.nav.logistics.provider.view.NavLogisticsProviderViewItemVo;
import com.fowo.api.model.nav.logistics.provider.view.NavLogisticsProviderViewSearchParamPo;
import com.fowo.api.model.nav.sell.order.declare.NavSellOrderDeclareSearchParamPo;
import com.fowo.api.model.nav.sell.order.detail.NavSellOrderDetailSearchParamPo;
import com.fowo.api.model.nav.sell.order.platform.NavSellOrderPlatformSearchParamPo;
import com.fowo.api.model.nav.sell.order.transaction.NavSellOrderTransactionSearchParamPo;
import com.fowo.api.model.shop.info.ShopInfoItemVo;
import com.fowo.api.model.shop.info.ShopInfoSearchParamPo;
import com.fowo.api.model.sys.region.SysRegionItemVo;
import com.fowo.api.model.sys.region.SysRegionSearchParamPo;
import com.fowo.api.service.IssuOrderService;
import com.fowo.api.service.NavSellOrderDeclareService;
import com.fowo.api.service.NavSellOrderDetailService;
import com.fowo.api.service.NavSellOrderPlatformService;
import com.fowo.api.service.NavSellOrderTransactionService;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 订单管理订单标发 服务实现基类
 * @author 蜂窝蜜造平台 配置人：任凯，沈友谅
 */
@Slf4j
@DataObjectType(IssuOrder.class)
@DS("ds24")
public class IssuOrderBaseServiceImpl
  extends ServiceImpl<IssuOrderMapper, IssuOrder>
  implements IssuOrderService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("shopInfoShopName", "si.`shop_name`");
      put("siteName", "sr.`name`");
      put("deliveryLogisticsLabel", "nlpv.`label`");
      put("deliveryLogisticsChannelLabel", "nlcv.`label`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected IssuOrderService self;

  @Resource
  protected NavSellOrderPlatformService navSellOrderPlatformService;

  @Resource
  protected NavSellOrderTransactionService navSellOrderTransactionService;

  @Resource
  protected NavSellOrderDetailService navSellOrderDetailService;

  @Resource
  protected NavSellOrderDeclareService navSellOrderDeclareService;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected ShopInfoMapper shopInfoMapper;

  @Resource
  protected SysRegionMapper sysRegionMapper;

  @Resource
  protected NavLogisticsProviderViewMapper navLogisticsProviderViewMapper;

  @Resource
  protected NavLogisticsChannelViewMapper navLogisticsChannelViewMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Autowired(required = false)
  protected IssuOrderMarkDeliveryAction issuOrderMarkDeliveryAction;

  @Autowired(required = false)
  protected IssuOrderUnMarkDeliveryAction issuOrderUnMarkDeliveryAction;

  @Resource
  protected Validator validator;

  /**
   * 创建订单管理订单标发
   * @param model 订单管理订单标发
   * @return 新数据的主键
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(IssuOrderVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    IssuOrder entity = new IssuOrder();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      return entity.getId();
    }
    throw new Exception("订单管理订单标发保存失败");
  }

  /**
   * 更新所有子表
   * @param model 订单管理订单标发
   */
  protected void updateAllChilds(IssuOrderVo model) throws Exception {
    if (model.getPlatform() != null) {
      navSellOrderPlatformService.saveAllByParentNavSellOrder(
        model.getId(),
        model.getPlatform()
      );
    }

    if (model.getTransaction() != null) {
      navSellOrderTransactionService.saveAllByParentNavSellOrder(
        model.getId(),
        model.getTransaction()
      );
    }

    if (model.getProduct() != null) {
      navSellOrderDetailService.saveAllByParentNavSellOrder(
        model.getId(),
        model.getProduct()
      );
    }

    if (model.getDeclare() != null) {
      navSellOrderDeclareService.saveAllByParentNavSellOrder(
        model.getId(),
        model.getDeclare()
      );
    }
  }

  /**
   * 更新订单管理订单标发
   * @param model 订单管理订单标发
   * @return 更新是否成功
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(IssuOrderVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    IssuOrder entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("订单管理订单标发不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser",
      "platform",
      "transaction",
      "product",
      "declare"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      return true;
    }
    return false;
  }/**
   * 更新订单管理订单标发（带空值）
   * @param model 订单管理订单标发
   * @return 更新是否成功
   */

  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(IssuOrderVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    IssuOrder entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("订单管理订单标发不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(IssuOrder::getLastUpdateTime, model.getLastUpdateTime())
      .set(IssuOrder::getLastUpdateUser, model.getLastUpdateUser())
      .set(IssuOrder::getOrderId, model.getOrderId())
      .set(IssuOrder::getStatus, model.getStatus())
      .set(IssuOrder::getShopInfo, model.getShopInfo())
      .set(IssuOrder::getSite, model.getSite())
      .set(IssuOrder::getDeliveryLogistics, model.getDeliveryLogistics())
      .set(
        IssuOrder::getDeliveryLogisticsChannel,
        model.getDeliveryLogisticsChannel()
      )
      .set(IssuOrder::getDeliveryIssuId, model.getDeliveryIssuId())
      .set(IssuOrder::getOnlineStatus, model.getOnlineStatus())
      .set(IssuOrder::getIssuStatus, model.getIssuStatus())
      .set(IssuOrder::getIssuStatusExplain, model.getIssuStatusExplain())
      .set(IssuOrder::getIssuNumber, model.getIssuNumber())
      .set(IssuOrder::getIssuTime, model.getIssuTime())
      .set(IssuOrder::getDeliveryWaybillId, model.getDeliveryWaybillId())
      .set(IssuOrder::getDeliveryTrackId, model.getDeliveryTrackId())
      .eq(IssuOrder::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(IssuOrderSearchParamPo search) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 平台信息(platform) 对应的对象
    NavSellOrderPlatformSearchParamPo platformSearchParam =
      new NavSellOrderPlatformSearchParamPo();
    platformSearchParam.setDisableDataPremissions(true);
    platformSearchParam.setParentNavSellOrderInList(ids);
    NavSellOrderPlatformMapper localNavSellOrderPlatformMapper = ContextHolder
      .getApplicationContext()
      .getBean(NavSellOrderPlatformMapper.class);
    platformSearchParam.applySqlSegments();
    List<Long> platformIdList = localNavSellOrderPlatformMapper.searchIds(
      platformSearchParam
    );
    if (!platformIdList.isEmpty()) {
      NavSellOrderPlatformService localNavSellOrderPlatformService =
        ContextHolder
          .getApplicationContext()
          .getBean(NavSellOrderPlatformService.class);
      localNavSellOrderPlatformService.batchDelete(platformIdList);
    }

    // 处理子表字段 交易信息(transaction) 对应的对象
    NavSellOrderTransactionSearchParamPo transactionSearchParam =
      new NavSellOrderTransactionSearchParamPo();
    transactionSearchParam.setDisableDataPremissions(true);
    transactionSearchParam.setParentNavSellOrderInList(ids);
    NavSellOrderTransactionMapper localNavSellOrderTransactionMapper =
      ContextHolder
        .getApplicationContext()
        .getBean(NavSellOrderTransactionMapper.class);
    transactionSearchParam.applySqlSegments();
    List<Long> transactionIdList = localNavSellOrderTransactionMapper.searchIds(
      transactionSearchParam
    );
    if (!transactionIdList.isEmpty()) {
      NavSellOrderTransactionService localNavSellOrderTransactionService =
        ContextHolder
          .getApplicationContext()
          .getBean(NavSellOrderTransactionService.class);
      localNavSellOrderTransactionService.batchDelete(transactionIdList);
    }

    // 处理子表字段 产品信息(product) 对应的对象
    NavSellOrderDetailSearchParamPo productSearchParam =
      new NavSellOrderDetailSearchParamPo();
    productSearchParam.setDisableDataPremissions(true);
    productSearchParam.setParentNavSellOrderInList(ids);
    NavSellOrderDetailMapper localNavSellOrderDetailMapper = ContextHolder
      .getApplicationContext()
      .getBean(NavSellOrderDetailMapper.class);
    productSearchParam.applySqlSegments();
    List<Long> productIdList = localNavSellOrderDetailMapper.searchIds(
      productSearchParam
    );
    if (!productIdList.isEmpty()) {
      NavSellOrderDetailService localNavSellOrderDetailService = ContextHolder
        .getApplicationContext()
        .getBean(NavSellOrderDetailService.class);
      localNavSellOrderDetailService.batchDelete(productIdList);
    }

    // 处理子表字段 报关信息(declare) 对应的对象
    NavSellOrderDeclareSearchParamPo declareSearchParam =
      new NavSellOrderDeclareSearchParamPo();
    declareSearchParam.setDisableDataPremissions(true);
    declareSearchParam.setParentNavSellOrderInList(ids);
    NavSellOrderDeclareMapper localNavSellOrderDeclareMapper = ContextHolder
      .getApplicationContext()
      .getBean(NavSellOrderDeclareMapper.class);
    declareSearchParam.applySqlSegments();
    List<Long> declareIdList = localNavSellOrderDeclareMapper.searchIds(
      declareSearchParam
    );
    if (!declareIdList.isEmpty()) {
      NavSellOrderDeclareService localNavSellOrderDeclareService = ContextHolder
        .getApplicationContext()
        .getBean(NavSellOrderDeclareService.class);
      localNavSellOrderDeclareService.batchDelete(declareIdList);
    }
  }

  /**
   * 删除订单管理订单标发
   * @param id 订单管理订单标发的主键
   * @return 删除是否成功
   */
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除订单管理订单标发
   * @param ids 订单管理订单标发的主键列表
   * @return 删除是否成功
   */
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);

    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<IssuOrderImportPo> excelToImportRow(
    IssuOrderImportPo row,
    Integer rowNumber,
    IssuOrderVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<IssuOrderImportPo> ir = new ImportRow<IssuOrderImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<IssuOrderImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new IssuOrderVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, IssuOrderImportPo.class);

    // 一般数据处理
    if (StringUtils.hasText(row.getStatus())) {
      List<SysDictAllItem> statusItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "status",
          n -> sysDictService.getDictItems("SCM00143")
        );
      IssuOrderVo finalVo = vo;
      statusItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getStatus()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setStatus(i.getItemValue()),
          () ->
            ir.addError(
              "status",
              String.format(
                "必须为 %s 中之一",
                statusItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getIssuStatus())) {
      List<SysDictAllItem> issuStatusItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "issuStatus",
          n -> sysDictService.getDictItems("SCM00160")
        );
      IssuOrderVo finalVo = vo;
      issuStatusItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getIssuStatus()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setIssuStatus(i.getItemValue()),
          () ->
            ir.addError(
              "issuStatus",
              String.format(
                "必须为 %s 中之一",
                issuStatusItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setIssuNumber(SheetUtils.tryToInteger(row.getIssuNumber()));
    vo.setIssuTime(SheetUtils.tryToDateTime(row.getIssuTime()));
    // 处理关联字段“店铺”
    if (
      !SheetUtils.isBlank(row.getShopInfoShopName()) &&
      SheetUtils.isBlank(row.getShopInfo())
    ) {
      ShopInfoSearchParamPo shopInfoSearchParam = new ShopInfoSearchParamPo();
      shopInfoSearchParam.setLimit(2); // 最大只返回二行记录
      shopInfoSearchParam.setShopNameEq(
        SheetUtils.trim(row.getShopInfoShopName())
      );
      shopInfoSearchParam.applySqlSegments();
      List<ShopInfoItemVo> shopInfoMatches = shopInfoMapper.search(
        shopInfoSearchParam
      );
      if (shopInfoMatches.size() == 0) {
        ir.addError("shopInfoShopName", "未能在店铺中找到匹配的数据");
      } else if (shopInfoMatches.size() > 1) {
        ir.addError(
          "shopInfoShopName",
          "关联不唯一，在店铺中找到多个匹配的数据"
        );
      } else {
        vo.setShopInfo(shopInfoMatches.get(0).getId());
      }
    }
    // 处理关联字段“站点”
    if (
      !SheetUtils.isBlank(row.getSiteName()) &&
      SheetUtils.isBlank(row.getSite())
    ) {
      SysRegionSearchParamPo siteSearchParam = new SysRegionSearchParamPo();
      siteSearchParam.setLimit(2); // 最大只返回二行记录
      siteSearchParam.setNameEq(SheetUtils.trim(row.getSiteName()));
      siteSearchParam.applySqlSegments();
      List<SysRegionItemVo> siteMatches = sysRegionMapper.search(
        siteSearchParam
      );
      if (siteMatches.size() == 0) {
        ir.addError("siteName", "未能在站点中找到匹配的数据");
      } else if (siteMatches.size() > 1) {
        ir.addError("siteName", "关联不唯一，在站点中找到多个匹配的数据");
      } else {
        vo.setSite(siteMatches.get(0).getId());
      }
    }
    // 处理关联字段“客选物流”
    if (
      !SheetUtils.isBlank(row.getDeliveryLogisticsLabel()) &&
      SheetUtils.isBlank(row.getDeliveryLogistics())
    ) {
      NavLogisticsProviderViewSearchParamPo deliveryLogisticsSearchParam =
        new NavLogisticsProviderViewSearchParamPo();
      deliveryLogisticsSearchParam.setLimit(2); // 最大只返回二行记录
      deliveryLogisticsSearchParam.setLabelEq(
        SheetUtils.trim(row.getDeliveryLogisticsLabel())
      );
      deliveryLogisticsSearchParam.applySqlSegments();
      List<NavLogisticsProviderViewItemVo> deliveryLogisticsMatches =
        navLogisticsProviderViewMapper.search(deliveryLogisticsSearchParam);
      if (deliveryLogisticsMatches.size() == 0) {
        ir.addError(
          "deliveryLogisticsLabel",
          "未能在物流管理-客选物流-视图中找到匹配的数据"
        );
      } else if (deliveryLogisticsMatches.size() > 1) {
        ir.addError(
          "deliveryLogisticsLabel",
          "关联不唯一，在物流管理-客选物流-视图中找到多个匹配的数据"
        );
      } else {
        vo.setDeliveryLogistics(deliveryLogisticsMatches.get(0).getId());
      }
    }
    // 处理关联字段“物流方式”
    if (
      !SheetUtils.isBlank(row.getDeliveryLogisticsChannelLabel()) &&
      SheetUtils.isBlank(row.getDeliveryLogisticsChannel())
    ) {
      NavLogisticsChannelViewSearchParamPo deliveryLogisticsChannelSearchParam =
        new NavLogisticsChannelViewSearchParamPo();
      deliveryLogisticsChannelSearchParam.setLimit(2); // 最大只返回二行记录
      deliveryLogisticsChannelSearchParam.setLabelEq(
        SheetUtils.trim(row.getDeliveryLogisticsChannelLabel())
      );
      deliveryLogisticsChannelSearchParam.applySqlSegments();
      List<NavLogisticsChannelViewItemVo> deliveryLogisticsChannelMatches =
        navLogisticsChannelViewMapper.search(
          deliveryLogisticsChannelSearchParam
        );
      if (deliveryLogisticsChannelMatches.size() == 0) {
        ir.addError(
          "deliveryLogisticsChannelLabel",
          "未能在物流管理-渠道基本信息-视图中找到匹配的数据"
        );
      } else if (deliveryLogisticsChannelMatches.size() > 1) {
        ir.addError(
          "deliveryLogisticsChannelLabel",
          "关联不唯一，在物流管理-渠道基本信息-视图中找到多个匹配的数据"
        );
      } else {
        vo.setDeliveryLogisticsChannel(
          deliveryLogisticsChannelMatches.get(0).getId()
        );
      }
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<IssuOrderImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<IssuOrderImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            IssuOrderImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(IssuOrderImportPo row, AnalysisContext cxt) {
              IssuOrderVo vo = new IssuOrderVo();
              ImportRow<IssuOrderImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<IssuOrderImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<IssuOrderImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      IssuOrderVo vo = new IssuOrderVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @Override
  public void export(
    Long templateId,
    IssuOrderSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "status",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00143")
      );
      exportOptions.addFieldMappingOption(
        "shopInfo",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((IssuOrderItemVo) r).getShopInfoShopName())
          )
      );
      exportOptions.addFieldMappingOption(
        "site",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((IssuOrderItemVo) r).getSiteName())
          )
      );
      exportOptions.addFieldMappingOption(
        "deliveryLogistics",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((IssuOrderItemVo) r).getDeliveryLogisticsLabel())
          )
      );
      exportOptions.addFieldMappingOption(
        "deliveryLogisticsChannel",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((IssuOrderItemVo) r).getDeliveryLogisticsChannelLabel()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "issuStatus",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00160")
      );
      exportOptions.addStringFields(
        "orderId",
        "status",
        "shopInfoShopName",
        "siteName",
        "deliveryLogisticsLabel",
        "deliveryLogisticsChannelLabel",
        "deliveryIssuId",
        "onlineStatus",
        "issuStatus",
        "issuStatusExplain",
        "deliveryWaybillId",
        "deliveryTrackId"
      );

      String fileName = String.format(
        "订单管理订单标发(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> statusItems = sysDictService.getDictItems("SCM00143");
    List<SysDictAllItem> issuStatusItems = sysDictService.getDictItems(
      "SCM00160"
    );
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<IssuOrderExcelPo> items = new ArrayList<IssuOrderExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<IssuOrderItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<IssuOrderItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (IssuOrderItemVo item : list) {
        IssuOrderExcelPo excel = new IssuOrderExcelPo();
        BeanUtils.copyProperties(item, excel);
        if (item.getStatus() != null) {
          statusItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getStatus()))
            .findFirst()
            .ifPresent(i -> excel.setStatus(i.getItemText()));
        }
        if (item.getIssuStatus() != null) {
          issuStatusItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getIssuStatus()))
            .findFirst()
            .ifPresent(i -> excel.setIssuStatus(i.getItemText()));
        }

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "订单管理订单标发(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(IssuOrderExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过系统单号查询订单管理订单标发主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByOrderId(String orderId) {
    return this.baseMapper.getIdByOrderId(orderId);
  }

  /**
   * 通过系统单号查询订单管理订单标发多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByOrderId(List<String> list) {
    return this.baseMapper.getIdsByOrderId(list);
  }

  /**
   * 通过订单管理订单标发主键查询系统单号
   */
  @Override
  public String getOrderIdById(Long id) {
    return this.baseMapper.getOrderIdById(id);
  }

  /**
   * 通过订单管理订单标发主键查询系统单号列表
   */
  @Override
  public List<String> getOrderIdByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getOrderIdByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("orderId"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 订单管理订单标发的主键
   */
  @Override
  public IssuOrderVo getVoById(Long id) throws Exception {
    IssuOrderVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    NavSellOrderPlatformSearchParamPo platformSearchParamPo =
      new NavSellOrderPlatformSearchParamPo();
    platformSearchParamPo.setParentNavSellOrder(id);
    platformSearchParamPo.getExtendData().put("queryMode", "sub");
    platformSearchParamPo.getExtendData().put("queryParent", "IssuOrder");
    platformSearchParamPo.applySqlSegments();
    vo.setPlatform(navSellOrderPlatformService.search(platformSearchParamPo));

    NavSellOrderTransactionSearchParamPo transactionSearchParamPo =
      new NavSellOrderTransactionSearchParamPo();
    transactionSearchParamPo.setParentNavSellOrder(id);
    transactionSearchParamPo.getExtendData().put("queryMode", "sub");
    transactionSearchParamPo.getExtendData().put("queryParent", "IssuOrder");
    transactionSearchParamPo.applySqlSegments();
    vo.setTransaction(
      navSellOrderTransactionService.search(transactionSearchParamPo)
    );

    NavSellOrderDetailSearchParamPo productSearchParamPo =
      new NavSellOrderDetailSearchParamPo();
    productSearchParamPo.setParentNavSellOrder(id);
    productSearchParamPo.getExtendData().put("queryMode", "sub");
    productSearchParamPo.getExtendData().put("queryParent", "IssuOrder");
    productSearchParamPo.applySqlSegments();
    vo.setProduct(navSellOrderDetailService.search(productSearchParamPo));

    NavSellOrderDeclareSearchParamPo declareSearchParamPo =
      new NavSellOrderDeclareSearchParamPo();
    declareSearchParamPo.setParentNavSellOrder(id);
    declareSearchParamPo.getExtendData().put("queryMode", "sub");
    declareSearchParamPo.getExtendData().put("queryParent", "IssuOrder");
    declareSearchParamPo.applySqlSegments();
    vo.setDeclare(navSellOrderDeclareService.search(declareSearchParamPo));

    return vo;
  }

  /**
   * 主列表上要附加“平台信息”子表的部分字段
   * @param items 项目列表
   * @param sort 子表排序
   */
  protected void fillPartOfPlatform(List<IssuOrderItemVo> items, String sort) {
    NavSellOrderPlatformSearchParamPo platformSearchParamPo =
      new NavSellOrderPlatformSearchParamPo();
    platformSearchParamPo.setSort(sort);
    platformSearchParamPo.setSelectFields(
      List.of("parentNavSellOrder", "carrier", "deliveryService", "platform")
    );
    platformSearchParamPo.setParentNavSellOrderInList(
      items.stream().map(IssuOrderItemVo::getId).collect(Collectors.toList())
    );
    navSellOrderPlatformService
      .search(platformSearchParamPo)
      .forEach(platform -> {
        IssuOrderItemVo item = ListUtils.find(
          items,
          i -> Objects.equals(i.getId(), platform.getParentNavSellOrder())
        );
        if (item == null) return;
        if (item.getPlatformCarrier() == null) {
          item.setPlatformCarrier(new ArrayList<>());
        }
        item.getPlatformCarrier().add(platform.getCarrier());

        if (item.getPlatformDeliveryService() == null) {
          item.setPlatformDeliveryService(new ArrayList<>());
        }
        item.getPlatformDeliveryService().add(platform.getDeliveryService());

        if (item.getPlatformPlatform() == null) {
          item.setPlatformPlatform(new ArrayList<>());
        }
        item.getPlatformPlatform().add(platform.getPlatform());
      });
  }

  /**
   * 分页查询订单管理订单标发
   * @param search 查询条件
   * @return 订单管理订单标发分页查询结果
   */
  @Override
  public Page<IssuOrderItemVo> pageSearch(IssuOrderSearchParamPo search) {
    Page<IssuOrderItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(IssuOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 订单管理订单标发快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'IssuOrderOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<IssuOrderItemVo>> searchOptions(
    IssuOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询订单管理订单标发
   * @param search 查询条件
   * @return 订单管理订单标发列表查询结果
   */
  @Override
  public List<IssuOrderItemVo> search(IssuOrderSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询订单管理订单标发最后更新时间
   * @param search 查询条件
   * @return 订单管理订单标发最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(IssuOrderSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 标发
   */
  @Override
  public void markDelivery(List<Long> ids) throws Exception {
    if (issuOrderMarkDeliveryAction == null) {
      throw new Exception("此操作当前不可用");
    }
    issuOrderMarkDeliveryAction.run(ids);
  }

  /**
   * 不标发
   */
  @Override
  public void unMarkDelivery(List<Long> ids) throws Exception {
    if (issuOrderUnMarkDeliveryAction == null) {
      throw new Exception("此操作当前不可用");
    }
    issuOrderUnMarkDeliveryAction.run(ids);
  }

  /**
   * 视图选项卡标题上显示计数
   */

  @Override
  public Map getTabHeaderShowTotal() {
    IssuOrderSearchParamPo search = new IssuOrderSearchParamPo();
    return MapUtil
      .builder()
      .put("AllIssu", this.baseMapper.allIssuCount(search))
      .put("WaitIssu", this.baseMapper.waitIssuCount(search))
      .put("UpdateIssu", this.baseMapper.updateIssuCount(search))
      .put("OnIssu", this.baseMapper.onIssuCount(search))
      .put("FailIssu", this.baseMapper.failIssuCount(search))
      .put("SuccessIssu", this.baseMapper.successIssuCount(search))
      .put("NoIssu", this.baseMapper.noIssuCount(search))
      .build();
  }

  /**
   * 全部
   */
  @Override
  public List<IssuOrderItemVo> allIssu(IssuOrderSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.allIssu(search);
  }

  /**
   * 全部分页
   */
  @Override
  public Page<IssuOrderItemVo> allIssuPage(IssuOrderSearchParamPo search) {
    Page<IssuOrderItemVo> allIssuPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return allIssuPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return allIssuPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    allIssuPage =
      this.baseMapper.allIssuPage(
          search.toPage(this.baseMapper.allIssuCount(search)),
          search
        );
    if (
      search.getFillParts() == null ||
      search.getFillParts().contains("platform")
    ) {
      fillPartOfPlatform(
        allIssuPage.getRecords(),
        search.toChildSort("platform")
      );
    }
    List<Long> recordIds = allIssuPage
      .getRecords()
      .stream()
      .map(IssuOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return allIssuPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return allIssuPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    allIssuPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return allIssuPage;
  }

  /**
   * 查询全部最后更新时间
   * @param search 查询条件
   * @return 全部最后更新时间
   */
  @Override
  public Date allIssuLastUpdateTime(IssuOrderSearchParamPo search) {
    return this.baseMapper.allIssuLastUpdateTime(search);
  }

  /**
   * 待标发
   */
  @Override
  public List<IssuOrderItemVo> waitIssu(IssuOrderSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.waitIssu(search);
  }

  /**
   * 待标发分页
   */
  @Override
  public Page<IssuOrderItemVo> waitIssuPage(IssuOrderSearchParamPo search) {
    Page<IssuOrderItemVo> waitIssuPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return waitIssuPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return waitIssuPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    waitIssuPage =
      this.baseMapper.waitIssuPage(
          search.toPage(this.baseMapper.waitIssuCount(search)),
          search
        );
    if (
      search.getFillParts() == null ||
      search.getFillParts().contains("platform")
    ) {
      fillPartOfPlatform(
        waitIssuPage.getRecords(),
        search.toChildSort("platform")
      );
    }
    List<Long> recordIds = waitIssuPage
      .getRecords()
      .stream()
      .map(IssuOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return waitIssuPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return waitIssuPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    waitIssuPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return waitIssuPage;
  }

  /**
   * 查询待标发最后更新时间
   * @param search 查询条件
   * @return 待标发最后更新时间
   */
  @Override
  public Date waitIssuLastUpdateTime(IssuOrderSearchParamPo search) {
    return this.baseMapper.waitIssuLastUpdateTime(search);
  }

  /**
   * 标发数据更新
   */
  @Override
  public List<IssuOrderItemVo> updateIssu(IssuOrderSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.updateIssu(search);
  }

  /**
   * 标发数据更新分页
   */
  @Override
  public Page<IssuOrderItemVo> updateIssuPage(IssuOrderSearchParamPo search) {
    Page<IssuOrderItemVo> updateIssuPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return updateIssuPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return updateIssuPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    updateIssuPage =
      this.baseMapper.updateIssuPage(
          search.toPage(this.baseMapper.updateIssuCount(search)),
          search
        );
    if (
      search.getFillParts() == null ||
      search.getFillParts().contains("platform")
    ) {
      fillPartOfPlatform(
        updateIssuPage.getRecords(),
        search.toChildSort("platform")
      );
    }
    List<Long> recordIds = updateIssuPage
      .getRecords()
      .stream()
      .map(IssuOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return updateIssuPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return updateIssuPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    updateIssuPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return updateIssuPage;
  }

  /**
   * 查询标发数据更新最后更新时间
   * @param search 查询条件
   * @return 标发数据更新最后更新时间
   */
  @Override
  public Date updateIssuLastUpdateTime(IssuOrderSearchParamPo search) {
    return this.baseMapper.updateIssuLastUpdateTime(search);
  }

  /**
   * 标发中
   */
  @Override
  public List<IssuOrderItemVo> onIssu(IssuOrderSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.onIssu(search);
  }

  /**
   * 标发中分页
   */
  @Override
  public Page<IssuOrderItemVo> onIssuPage(IssuOrderSearchParamPo search) {
    Page<IssuOrderItemVo> onIssuPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return onIssuPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return onIssuPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    onIssuPage =
      this.baseMapper.onIssuPage(
          search.toPage(this.baseMapper.onIssuCount(search)),
          search
        );
    if (
      search.getFillParts() == null ||
      search.getFillParts().contains("platform")
    ) {
      fillPartOfPlatform(
        onIssuPage.getRecords(),
        search.toChildSort("platform")
      );
    }
    List<Long> recordIds = onIssuPage
      .getRecords()
      .stream()
      .map(IssuOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return onIssuPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return onIssuPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    onIssuPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return onIssuPage;
  }

  /**
   * 查询标发中最后更新时间
   * @param search 查询条件
   * @return 标发中最后更新时间
   */
  @Override
  public Date onIssuLastUpdateTime(IssuOrderSearchParamPo search) {
    return this.baseMapper.onIssuLastUpdateTime(search);
  }

  /**
   * 标发失败
   */
  @Override
  public List<IssuOrderItemVo> failIssu(IssuOrderSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.failIssu(search);
  }

  /**
   * 标发失败分页
   */
  @Override
  public Page<IssuOrderItemVo> failIssuPage(IssuOrderSearchParamPo search) {
    Page<IssuOrderItemVo> failIssuPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return failIssuPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return failIssuPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    failIssuPage =
      this.baseMapper.failIssuPage(
          search.toPage(this.baseMapper.failIssuCount(search)),
          search
        );
    if (
      search.getFillParts() == null ||
      search.getFillParts().contains("platform")
    ) {
      fillPartOfPlatform(
        failIssuPage.getRecords(),
        search.toChildSort("platform")
      );
    }
    List<Long> recordIds = failIssuPage
      .getRecords()
      .stream()
      .map(IssuOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return failIssuPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return failIssuPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    failIssuPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return failIssuPage;
  }

  /**
   * 查询标发失败最后更新时间
   * @param search 查询条件
   * @return 标发失败最后更新时间
   */
  @Override
  public Date failIssuLastUpdateTime(IssuOrderSearchParamPo search) {
    return this.baseMapper.failIssuLastUpdateTime(search);
  }

  /**
   * 标发成功
   */
  @Override
  public List<IssuOrderItemVo> successIssu(IssuOrderSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.successIssu(search);
  }

  /**
   * 标发成功分页
   */
  @Override
  public Page<IssuOrderItemVo> successIssuPage(IssuOrderSearchParamPo search) {
    Page<IssuOrderItemVo> successIssuPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return successIssuPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return successIssuPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    successIssuPage =
      this.baseMapper.successIssuPage(
          search.toPage(this.baseMapper.successIssuCount(search)),
          search
        );
    if (
      search.getFillParts() == null ||
      search.getFillParts().contains("platform")
    ) {
      fillPartOfPlatform(
        successIssuPage.getRecords(),
        search.toChildSort("platform")
      );
    }
    List<Long> recordIds = successIssuPage
      .getRecords()
      .stream()
      .map(IssuOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return successIssuPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return successIssuPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    successIssuPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return successIssuPage;
  }

  /**
   * 查询标发成功最后更新时间
   * @param search 查询条件
   * @return 标发成功最后更新时间
   */
  @Override
  public Date successIssuLastUpdateTime(IssuOrderSearchParamPo search) {
    return this.baseMapper.successIssuLastUpdateTime(search);
  }

  /**
   * 不标发
   */
  @Override
  public List<IssuOrderItemVo> noIssu(IssuOrderSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.noIssu(search);
  }

  /**
   * 不标发分页
   */
  @Override
  public Page<IssuOrderItemVo> noIssuPage(IssuOrderSearchParamPo search) {
    Page<IssuOrderItemVo> noIssuPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return noIssuPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return noIssuPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    noIssuPage =
      this.baseMapper.noIssuPage(
          search.toPage(this.baseMapper.noIssuCount(search)),
          search
        );
    if (
      search.getFillParts() == null ||
      search.getFillParts().contains("platform")
    ) {
      fillPartOfPlatform(
        noIssuPage.getRecords(),
        search.toChildSort("platform")
      );
    }
    List<Long> recordIds = noIssuPage
      .getRecords()
      .stream()
      .map(IssuOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return noIssuPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return noIssuPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    noIssuPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return noIssuPage;
  }

  /**
   * 查询不标发最后更新时间
   * @param search 查询条件
   * @return 不标发最后更新时间
   */
  @Override
  public Date noIssuLastUpdateTime(IssuOrderSearchParamPo search) {
    return this.baseMapper.noIssuLastUpdateTime(search);
  }
}
